//
//  RHUploadVideoVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/7/11.
//

#import "RHUploadVideoVC.h"
#import "RHSelectPlantVC.h"
#import "RHPlantModel.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import "RHVideoManager.h"
#import "NetworkConfig.h"

@interface RHUploadVideoVC ()
@property (nonatomic, strong) NSURL *videoUrl;//视频本地地址

@property (nonatomic, strong) UIImage *coverImage;//封面

@property (nonatomic, strong, nullable) SJVideoPlayer *player;

@property (nonatomic, strong) QMUITextField *titleTextField;

@property (nonatomic, strong) QMUITextField *plantTextField;

@property (nonatomic ,strong) RHPlantModel *plantModel;

@property (nonatomic ,strong) UIView *videoView;

@property (nonatomic ,strong) UIImageView *coverImageView;
@end

@implementation RHUploadVideoVC
-(instancetype)initWithVideoUrl:(NSURL*)videoUrl coverImage:(UIImage*)coverImage
{
    if (self = [super init]) {
        _videoUrl = videoUrl;
        _coverImage = coverImage;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
//    [self initPlayer];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)initPlayer{
    if ( !_player ) {
        _player = [SJVideoPlayer player];
        
    }
    [self.videoView addSubview:_player.view];
    [_player.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    _player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:self.videoUrl];
    _player.URLAsset.title = @"";
   
  
    _player.rotationObserver.onRotatingChanged = ^(id<SJRotationManager>  _Nonnull mgr, BOOL isRotating) {
        if(isRotating  ){
            if(mgr.currentOrientation == 3){
                [AppDelegate shareAppDelegate].allowRotate = YES;
            }else{
                [AppDelegate shareAppDelegate].allowRotate = NO;
            }
            
        }
    
    };
}

-(void)setupUI
{
    UIView *navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kNavHeight)];
    [self.view addSubview:navView];
    navView.backgroundColor = UIColor.whiteColor;
    QMUIButton *backBtn = [[QMUIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"back_close"] forState:UIControlStateNormal];
    [navView addSubview: backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.left.mas_offset(10);
        make.bottom.mas_offset(-10);
    }];
    
    QMUIButton *shareBtn = [[QMUIButton alloc]init];
    [shareBtn setTitle:@"分享".rh_localized forState:UIControlStateNormal];
    shareBtn.titleLabel.font = kSYSTEMFONT(14);
    [shareBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [shareBtn setCornerRadius:8];
    [shareBtn setGradientBackgroundWithColors:@[kCOLOR_HEX(@"6AD785"),kCOLOR_HEX(@"5ECBB7")] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
    [navView addSubview: shareBtn];
    CGFloat width = [shareBtn.titleLabel.text getStringWidthFont:shareBtn.titleLabel.font limitHeight:20];
    [shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(width+15);
        make.height.offset(30);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(-10);
    }];
    
    kWeakSelf;
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    [[shareBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf uploadVideo];
    }];
    
    UIView *bgView = kView;
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(navView.mas_bottom).offset(15);
        make.bottom.mas_offset(-15);
    }];
    
    QMUITextField *textField = [[QMUITextField alloc]init];
    textField.font = kSYSTEMFONT(14);
    textField.placeholder = @"请输入标题".rh_localized;
    textField.maximumTextLength = 200;
    [bgView addSubview:textField];
    self.titleTextField = textField;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(40);
    }];
    
    UIView *videoView = kView;
    videoView.backgroundColor = CFTabViewBgColor;
    videoView.layer.cornerRadius = 8;
    videoView.clipsToBounds = YES;
    [bgView addSubview:videoView];
    self.videoView = videoView;
    [videoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.right.mas_offset(-10);
        make.top.equalTo(textField.mas_bottom).offset(5);
        make.height.equalTo(videoView.mas_width).multipliedBy(160.0/315.0);
    }];
    
    _coverImageView = [[UIImageView alloc]init];
    _coverImageView.contentMode = UIViewContentModeScaleAspectFill;
    if (self.coverImage) {
        _coverImageView.image = self.coverImage;
    }
    [videoView addSubview:_coverImageView];
    [_coverImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    QMUIButton *playBtn = [[QMUIButton alloc]init];
    [playBtn setImage:[UIImage imageNamed:@"service_video_play"] forState:UIControlStateNormal];
    [videoView addSubview:playBtn];
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(45);
        make.center.mas_offset(0);
    }];
    
    
    UIView *addCoverView = [[UIView alloc]init];
    [addCoverView setBackgroundColor:kCOLOR_HEX_A(@"000000", 0.2)];
    addCoverView.layer.cornerRadius = 8;
    addCoverView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [bgView addSubview:addCoverView];
    [addCoverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(videoView);
        make.height.offset(30);
    }];
    
    QMUIButton *addCoverBtn = [[QMUIButton alloc]init];
    [addCoverBtn setTitle:@"添加封面".rh_localized forState:UIControlStateNormal];
    addCoverBtn.titleLabel.font = kSYSTEMFONT(12);
    [addCoverBtn setTitleColor:kCOLOR_HEX_A(@"ffffff", 0.8) forState:UIControlStateNormal];
    [addCoverView addSubview: addCoverBtn];
    CGFloat btnWidth = [addCoverBtn.titleLabel.text getStringWidthFont:addCoverBtn.titleLabel.font limitHeight:25];
    [addCoverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(videoView);
        make.height.offset(30);
        make.width.offset(btnWidth+2);
        make.centerX.mas_offset(0);
    }];
    
   
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"#EBEDF0");
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.right.mas_offset(-10);
        make.top.equalTo(videoView.mas_bottom).offset(15);
        make.height.offset(1);
    }];
    
    QMUIButton *selectBtn = [[QMUIButton alloc]init];
    [bgView addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(line.mas_bottom).offset(5);
        make.height.offset(40);
    }];
    
    
    
    
    UIImageView *arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow"]];
    [bgView addSubview:arrow];
    [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.right.mas_offset(-10);
        make.centerY.equalTo(selectBtn);
    }];
    
    
    _plantTextField = [[QMUITextField alloc]init];
    _plantTextField.placeholder = @"请选择所属电站".rh_localized;
    _plantTextField.font = kSYSTEMFONT(14);
    _plantTextField.textColor = kCOLOR_HEX(@"#BBBBBB");
    _plantTextField.textAlignment = NSTextAlignmentLeft;
    _plantTextField.userInteractionEnabled = NO;
    [bgView addSubview:_plantTextField];
 
    [_plantTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn).offset(15);
        make.centerY.equalTo(selectBtn);
        make.right.equalTo(arrow.mas_left).offset(-5);
    }];
    
    [[playBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf initPlayer];
    }];
    
    [[addCoverBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf addPhotoFromAlbum:NO];
    }];
    
    [[selectBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf selectPlant];
    }];
}

#pragma mark ------- 分享视频
-(void)uploadVideo
{
    if(self.titleTextField.text.length == 0 || [NSString checkIsAllEmptyLater:self.titleTextField.text]){
        [QMUITips showInfo:@"请输入标题".rh_localized];
        return;
    }
    if(self.plantTextField.text.length == 0){
        [QMUITips showInfo:@"请选择电站".rh_localized];
        return;
    }
    if (self.coverImageView.image == nil) {
        [QMUITips showInfo:@"请选择封面".rh_localized];
        return;
    }
    [RHVideoManager shareInstance].uploadPara = @{@"title":self.titleTextField.text,
                                                  @"plantId":@(self.plantModel.plant_id),
                                                  @"productType":self.plantModel.productTypeCode,
                                                  @"userId":@([PrivateMange share].currentUser.userId),
                                                  @"language":[NetworkConfig sharedConfig].language
    };
    [[RHVideoManager shareInstance]uploadVideoWithUrl:self.videoUrl coverImage:self.coverImageView.image];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ------- 选择电站
-(void)selectPlant{
    RHSelectPlantVC *selectVC = [[RHSelectPlantVC alloc]init];
    selectVC.curPlant = self.plantModel;
    kWeakSelf;
    selectVC.selectBlock = ^(RHPlantModel * plantModel) {
        weakSelf.plantModel = plantModel;
        self.plantTextField.text = plantModel.plantName;
    };
    [self.navigationController pushViewController:selectVC animated:YES];
}



#pragma mark - Action
- (void)addPicAction{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"相机".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO];
        
   }];
}


//从相机拍照
- (void)addPhotoFromCamera{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = NO;
    camera.allowRecordVideo = YES;
    
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        weakSelf.coverImageView.image = image;
    };
    [self showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    
    actionSheet.configuration.maxSelectCount = 1;
    actionSheet.configuration.mutuallyExclusiveSelectInMix = YES;
    
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    //设置是否允许选择图片
    actionSheet.configuration.allowSelectImage = YES;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑
    actionSheet.configuration.allowEditImage = YES;
    
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = [UIColor whiteColor];
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    
    actionSheet.sender = self;

    [actionSheet showPhotoLibrary];
    PHAssetResource *av;
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        weakSelf.coverImageView.image = [images firstObject];
    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
        
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}

//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}
@end
